﻿#include <QJsonObject>
#include <QQmlContext>
#include <PluginsAction.h>
#include "FavoriteAttributes.h"
#include "AttributeGroup.h"
#include "QmlEventGroup.h"
#include "QmlEventGroup_global.h"

QStringView QmlEventGroup::name() const {
	return QStringView(u"QmlAttributes");
}

bool QmlEventGroup::load(QString const& cfgFile /*= QString()*/) {
	bool result = false;	
	result = QMetaObject::invokeMethod(m_pluginAction->context(), [this]() {
		auto fa = new FavoriteAttributes;
		m_ag = new AttributeGroup(fa);
		fa->moveToThread(m_pluginAction->context()->thread());
		m_ag->moveToThread(m_pluginAction->context()->thread());
		m_pluginAction->context()->setContextProperty("favorite", fa);
		m_pluginAction->context()->setContextProperty("attributes", m_ag);
		connect(fa, &FavoriteAttributes::message, this, &QmlEventGroup::onMessage);
		connect(this, &QObject::destroyed, m_ag, &QObject::deleteLater);
		connect(this, &QObject::destroyed, fa, &QObject::deleteLater);
		emit loadFinished(name().toString());
	});
	return result;
}

void QmlEventGroup::logsEvent(QJsonObject const& logsObj) {}

void QmlEventGroup::sensorsEvent(QJsonObject const& valuesObj) {
	QMetaObject::invokeMethod(this, [valuesObj, this] {
		updateData(std::move(valuesObj));
	});
};

QStringList QmlEventGroup::subTopic() const {
	return QStringList() << "sensors" << "recv:SimAction";
}

void QmlEventGroup::handleMessage(QStringView topic, QByteArray payload) {
	std::ignore = topic;
	std::ignore = payload;
}

QStringList QmlEventGroup::commands() const {
	return QStringList() << "setWorkMode";
}

void QmlEventGroup::onMessage(QJsonObject const& msg) {
	QJsonObject obj;
	obj["command"] = "setWorkMode";
	obj["message"] = msg;
	m_pluginAction->operate(obj);
}

void QmlEventGroup::updateData(QJsonObject const& obj) {
	m_ag->updateLast(obj);
}

extern "C" {
	QMLATTRIBUTES_EXPORT Plugin* make_plugin(PluginAction* pa) {
		return new QmlEventGroup(pa);
	}
}